import { _decorator, Component, EventTouch, instantiate, Label, Node, Prefab, Sprite } from 'cc';
import { Building } from '../entity/Buildings';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { EventManager } from '../event/EventManager';
import { ComfirmArmy } from './ComfirmArmy';
import { raceType } from '../settings/const';
const { ccclass, property } = _decorator;

@ccclass('SelectBuilding')
export class SelectBuilding extends Component {
    @property(Node)
    close:Node
    @property(Node)
    content:Node
    @property(Prefab)
    selectBuildingItem:Prefab

    _buildingList:Building[] = []

    async start() {
        this.close.on(Node.EventType.TOUCH_END, this.onClose, this)

        let comfrimArmy = UIManager.instance.getUI(PrefabEnum.ComfirmArmy).getComponent(ComfirmArmy)
        let race = comfrimArmy._village.user.uInfo.race
        
        this._buildingList = Building.createAllBuilding(race)
        this._buildingList[0].id = 99
        this._buildingList[0].name = '随机'

        for(let item of this._buildingList){
            let node = instantiate(this.selectBuildingItem)
            this.content.addChild(node)
            node.getChildByName('Label').getComponent(Label).string = item.name
            
            node.getChildByName('Sprite').getComponent(Sprite).spriteFrame = await item.getImg(race)
            node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        }
    }

    onTouchEnd(e:EventTouch){
        let name = e.currentTarget.getChildByName('Label').getComponent(Label).string
        for(let b of this._buildingList){
            if(b.name == name){
                EventManager.instance.emit(EventManager.EventType.SelectBuilding, b)
            }
        }
        UIManager.instance.closeUI(PrefabEnum.SelectBuilding)
    }

    onClose(){
        UIManager.instance.closeUI(PrefabEnum.SelectBuilding)
    }
}


